import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'

const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home')
const Login = () => import('@/views/login')
const My = () => import('@/views/my')
const Square = () => import('@/views/square')
const User = () => import('@/views/user')
const UserEdit = () => import('@/views/user/components/user-edit')
const UserPasswod = () => import('@/views/user/components/user-password')
const WordIndex = () => import('@/views/word/')
// 单词测试模块路由
const CourseIndex = () => import('@/views/course')
const WordList = () => import('@/views/course/components/wordlist')
const testMate = () => import('@/views/course/components/test-mated')
const testDictation = () => import('@/views/course/components/test-dictation')
const testWrite = () => import('@/views/course/components/test-writeEn')
const pointShow = () => import('@/views/course/components/point-show')
// 翻译模块路由
const translater = () => import('@/views/Translation/index.vue')
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: Home },
      { path: 'my', component: My },
      { path: 'Square', component: Square },
      { path: '/translation', component: translater }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/user',
    component: User,
    children: [
      { path: 'profile', component: UserEdit },
      { path: 'password', component: UserPasswod }
    ]
  },
  {
    path: '/word',
    component: WordIndex
  },
  {
    path: '/courses',
    component: CourseIndex,
    children: [
      { path: '', component: WordList },
      { path: 'mated', component: testMate },
      { path: 'dictation', component: testDictation },
      { path: 'write', component: testWrite },
      { path: 'point', component: pointShow }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  // 获取token
  const { profile } = store.state.user
  // 2. 判断是否有token
  const tokenStr = profile.token
  if (!tokenStr) return next('/login')
  next()
})

export default router
